package com.cloud.flowable.controller;

import com.cloud.common.domain.Result;
import com.cloud.controller.BaseController;
import com.cloud.enums.BusinessType;
import com.cloud.flowable.entity.bo.ProcessPage;
import com.cloud.flowable.entity.WfForm;
import com.cloud.flowable.service.IWfDeployFormService;
import com.cloud.flowable.service.IWfDeployService;
import com.cloud.logs.Logs;
import com.cloud.security.aop.RequestPermissions;
import com.cloud.utils.JSONUtils;
import com.cloud.utils.ToolUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Tag(name = "流程部署")
@RestController
@RequestMapping("/flowable/deploy")
public class WfDeployController extends BaseController {

    @Autowired
    private IWfDeployService deployService;

    @Autowired
    private IWfDeployFormService deployFormService;

    @Operation(summary = "查询流程部署分页列表")
    @RequestPermissions("flowable:deploy:list")
    @GetMapping("/list")
    public Result list(ProcessPage procPage) {
        return Result.success("查询成功", deployService.queryPageList(procPage));
    }

    @Operation(summary = "查询流程部署版本列表")
    @RequestPermissions("flowable:deploy:publishList")
    @GetMapping("/publishList")
    public Result publishList(ProcessPage procPage) {
        return Result.success("查询成功", deployService.queryPublishList(procPage));
    }

    @Operation(summary = "激活或挂起流程")
    @RequestPermissions("flowable:deploy:state")
    @PostMapping(value = "/changeState")
    public Result changeState(@RequestParam String state, @RequestParam String definitionId) {
        deployService.updateState(definitionId, state);
        return Result.success("激活或挂起流程");
    }

    @Operation(summary = "读取xml文件")
    @RequestPermissions("flowable:deploy:query")
    @GetMapping("/bpmnXml")
    public Result getBpmnXml(String definitionId) {
        return Result.success("查询成功", deployService.queryBpmnXmlById(definitionId));
    }

    @Operation(summary = "删除流程模型")
    @RequestPermissions("flowable:deploy:remove")
    @Logs(title = "删除流程部署", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    public Result remove(String deployIds) {
        List<String> ids = ToolUtils.setStrToList(deployIds);
        deployService.deleteByIds(ids);
        return Result.success("操作成功");
    }

    @Operation(summary = "查询流程部署关联表单信息")
    @GetMapping("/form")
    public Result start(String deployId) {
        WfForm wfForm = deployFormService.selectDeployFormById(deployId);
        if (Objects.isNull(wfForm)) {
            return Result.success("请先配置流程表单");
        }
        Map map = JSONUtils.toObject(wfForm.getContent(), Map.class);
        return Result.success("查询成功", map);
    }

}
